package l2ft.gameserver.templates.item;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class FightClubShopItems
{
	private static FightClubShopItems _instance;
	private final FightClubShopItem[] _fightClubShopItems;
	
	public FightClubShopItems()
	{
		_fightClubShopItems = loadFightClubShopItems();
	}
	
	public FightClubShopItem getItemByItemId(int itemId)
	{
		for(FightClubShopItem item : _fightClubShopItems)
			if(item.getItemId() == itemId)
				return item;
		return null;
	}
	
	public FightClubShopItem[] getItems()
	{
		return _fightClubShopItems;
	}
	
	public class FightClubShopItem
	{
		private final int _itemId;
		private final int _badgesNeeded;
		private final String _title;
		private final String _desc;
		
		public FightClubShopItem(int itemId, int badgesNeeded, String title, String desc)
		{
			_itemId = itemId;
			_badgesNeeded = badgesNeeded;
			_title = title;
			_desc = desc;
		}
		
		public int getItemId()
		{
			return _itemId;
		}
		
		public int getBadgesNeeded()
		{
			return _badgesNeeded;
		}
		
		public String getTitle()
		{
			return _title;
		}
		
		public String getDesc()
		{
			return _desc;
		}
	}
	
	private FightClubShopItem[] loadFightClubShopItems()
	{
		List<FightClubShopItem> items = new ArrayList<>();
		try
		{
			DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = docBuilderFactory.newDocumentBuilder();
            Document doc = db.parse(new File("data/xml/other/fight_club_shop.xml"));
            
            NodeList list = doc.getElementsByTagName("item");
			for (int i = 0; i < list.getLength(); i++)
			{
				Element element = (Element) list.item(i);
				String id = element.getAttribute("id");
				String badgesNeeded = element.getAttribute("badges");
				String name = element.getAttribute("name");
				String desc = element.getAttribute("desc");
				items.add(new FightClubShopItem(Integer.parseInt(id), Integer.parseInt(badgesNeeded), name, desc));
		  	}
		}
		catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		FightClubShopItem[] changedItems = new FightClubShopItem[items.size()];
		
		for(int i = 0;i<items.size();i++)
			changedItems[i] = items.get(i);
		
		return changedItems;
	}
	
	public static FightClubShopItems getInstance()
	{
		if(_instance == null)
			_instance = new FightClubShopItems();
		return _instance;
	}
}
